import { atom, selector } from 'recoil';
import { getStorage, setStorage, clearStorage } from '@/utils/storage';

const initialState: { username: string; token: string; auth: string[] } = {
    username: getStorage<string>('username') || '',
    token: getStorage<string>('token') || '',
    auth: getStorage<string[]>('auth') || [],
};

export const userStateAtom = atom({
    key: 'userStateAtom',
    default: initialState,
});

export const userSelector = selector({
    key: 'userSelector',
    get: ({ get }) => get(userStateAtom),
    set: ({ set }, newValue: any) => {
        if (!newValue) {
            set(userSelector, {
                username: '',
                token: '',
                auth: [],
            });
            clearStorage();
        } else {
            set(userStateAtom, newValue);
            setStorage('username', newValue?.username);
            setStorage('token', newValue?.token);
            setStorage('auth', newValue?.auth);
        }
    },
});
